/*************************************************************************
 * File Name:    Binary_Tree_Postorder_Traversal.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/18 14:09:09
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Binary Tree Postorder Traversal
 |
 | Given a binary tree, return the postorder traversal of its nodes' values.
 |
 | For example:
 | Given binary tree {1,#,2,3},
 | 1
 |  \
 |   2
 |  /
 | 3
 | return [3,2,1].
 |
 | Note: Recursive solution is trivial, could you do it iteratively?
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root)
    {
        stack<TreeNode*> left, right;
        vector<int> ans;
        TreeNode *p;
        
        for (p = root; p != NULL; p = p->left) {
            left.push(p);
        }
        
        while (true) {
            while (!left.empty() && !right.empty() && left.top() == right.top()) {
                ans.push_back(left.top()->val);
                left.pop();
                right.pop();
            }
            if (left.empty()) break;
            
            right.push(left.top());
            for (p = left.top()->right; p != NULL; p = p->left) {
                left.push(p);
            }
        }
        return ans;
    }
};

int
main(int argc, char *argv[])
{
    Solution sol;
    TreeNode *root = new TreeNode(1);
    root->right = new TreeNode(4);

    root->right->left = new TreeNode(3);
    root->right->left->right = new TreeNode(2);

    vector<int> ans = sol.postorderTraversal(root);
    for (size_t i = 0; i < ans.size(); ++i) {
        cout << ans[i] << " ";
    }
    cout << endl;
    return 0;
}
